<template>
  <el-drawer v-model="DrawerMessage.isflag" :title="DrawerMessage.title" :direction="direction">
    <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="120px" class="demo-ruleForm"
      :size="formSize" status-icon>
      <el-form-item label="上传图片" prop="image">
        <!-- <el-input v-model="ruleForm.image" /> -->
        <el-upload class="avatar-uploader" action="https://node-text-111992-4-1308764981.sh.run.tcloudbase.com/image/upload" :show-file-list="false"
          :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
          <img v-if="imageUrl" :src="imageUrl" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon">
            <Plus />
          </el-icon>
        </el-upload>

      </el-form-item>
      <el-form-item label="商品名称" prop="name">
        <el-input v-model="ruleForm.name" />
      </el-form-item>
      <el-form-item label="商品价格" prop="name">
        <el-input v-model="ruleForm.price" />
      </el-form-item>
      <el-form-item label="总库存" prop="name">
        <el-input v-model="ruleForm.inventory" />
      </el-form-item>
      <el-form-item label="商品分类" prop="name">
        <el-select v-model="ruleForm.active" class="m-2" placeholder="请选择分类" size="large">
          <el-option v-for="item in options" :key="item.title" :label="item.title" :value="item.title" />
        </el-select>
      </el-form-item>
      <el-form-item label="商品规格" prop="name">
        <div style="width: 100%;">
          <el-button @click="addGuige">点击添加</el-button>
        </div>
        <div v-for="(item,index) in guigeIndex">
          <div>
            <span>规格名：</span>
            <el-input class="w-70" v-model="item.headerValue"></el-input>
            <el-button type="danger">删除</el-button>
          </div>
          <div>
            <span>规格值：</span>
            <el-tag v-for="tag in item.dynamicTags" :key="tag" closable :disable-transitions="false"
              @close="handleClose(tag,index)">
              {{ tag }}
            </el-tag>
            <el-input v-if="item.inputVisible" ref="item.InputRef" v-model="item.inputValue" class="w-20" size="small"
              @keyup.enter="handleInputConfirm(index)" @blur="handleInputConfirm(index)" />
            <el-button v-else class="button-new-tag" size="small" @click="showInput(index)">
              + 添加规格
            </el-button>
          </div>
        </div>
      </el-form-item>


    </el-form>
    <div class="demo-drawer__footer">
      <el-button @click="cancelForm">取消</el-button>
      <el-button type="primary" @click="onClick">确定</el-button>
    </div>
  </el-drawer>
</template>

<script>
import {nextTick, ref, reactive, defineComponent, toRaw } from 'vue';
import emitter from '../mitt/index';
import { ElMessage } from 'element-plus'
// import  Node from 'element-plus/es/components/tree/src/model/node'

import { AddList, updateList, getListSort } from "../API/index"
import { Plus } from '@element-plus/icons-vue'
import { ElInput } from 'element-plus'
export default defineComponent({

  setup(props, { emit }) {
    // 添加规格
    const guigeIndex = reactive([])
    const inputValue = ref('')
const dynamicTags = ref([])
const inputVisible = ref(false)
const InputRef = ref()
// 添加规格按钮
const addGuige = ()=>{
  guigeIndex.push({headerValue:'',inputValue:'',dynamicTags:[],inputVisible:false,InputRef:null})
}
const handleClose = (tag,index) => {
  guigeIndex[index].dynamicTags.splice(guigeIndex[index].dynamicTags.indexOf(tag), 1)
  
}

const showInput = (index) => {
  guigeIndex[index].inputVisible = true
  nextTick(() => {
    guigeIndex[index].InputRef.input.focus()
  })
}

const handleInputConfirm = (index) => {
  if (guigeIndex[index].inputValue) {
    guigeIndex[index].dynamicTags.push(guigeIndex[index].inputValue)
  }
  guigeIndex[index].inputVisible = false
  guigeIndex[index].inputValue = ''
}
    const imageUrl = ref('')

    let DrawerMessage = reactive({ isflag: false, title: '' })
    // 商品分类
    const options = [
      // { value: '新品', label: '新品' },
      // { value: '咖啡', label: '咖啡' },
    ]
    // 选择添加的数据集合
    let ruleForm = reactive({ active: '', ruleName: '', name: '', image: '', inventory: '', price: '', shelfOrNot: true, sales: 0 })
    // 商品规则
    const commonityRule = [{ name: '咖啡', label: '咖啡' }, { name: '奶茶', label: '奶茶' }]
    const direction = ref('rtl')
    // 获取商品分类
    let getSort = async () => {
      let { data } = await getListSort()
      data.map(item => { if (item.checked) { options.push(item) } })
      
    }
    getSort()
    // 兄弟组件传递数据
    emitter.on('DrawerMessage', (res) => {
      // 清空对象
      // 未写


      DrawerMessage.isflag = res.isflag
      DrawerMessage.title = res.title
      if (res.DrawerMessage.title === '修改') {
        DrawerMessage.isflag = res.DrawerMessage.isflag
        DrawerMessage.title = res.DrawerMessage.title
        Object.assign(ruleForm, res.context)
        guigeIndex.length=0
        JSON.parse(res.context.ruleName).map(item=>{
          guigeIndex.push(item)
        })
      }
    })
    // 上传图片
    const handleAvatarSuccess = (
      response,
      uploadFile
    ) => {
      imageUrl.value = URL.createObjectURL(uploadFile.raw)

      ruleForm.image = response.imageUrl
      console.log(response);
    }
    // 确定添加按钮
    const onClick = async () => {
      ruleForm.ruleName=JSON.stringify(toRaw(guigeIndex))

      if (DrawerMessage.title === '添加') {
        // 接收过来的数据
        let data = await AddList({ ruleform: toRaw(ruleForm) })
        // console.log(toRaw(guigeIndex));
        
      } else {//修改
        let data = await updateList({ ruleForm: toRaw(ruleForm) })
      }
      ElMessage({
        message: `${DrawerMessage.title}成功`,
        type: 'success',
      })
      DrawerMessage.isflag = false
      // 通知table组件更新数据
      emitter.emit('updateTable')

    }
    // 取消按钮
    const cancelForm = () => {
      DrawerMessage.isflag = false
      ElMessage({
        message: '取消添加',
        type: 'warning',
      })
    }

    return {
      addGuige,guigeIndex,
      dynamicTags,handleClose,inputVisible,InputRef,inputValue,handleInputConfirm,handleInputConfirm,showInput,
       ruleForm, onClick, commonityRule, direction, options, props, DrawerMessage, imageUrl, handleAvatarSuccess }
  }
})

</script>

<style scoped>
.demo-drawer__footer {
  position: absolute;
  bottom: 20px;
  right: 20px;
}

.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>